//
//  XiaoximenTimelineViewController.m
//  Xiaoximen_iOS
//
//  Created by Wang Zhongyu on 12-7-18.
//  Copyright (c) 2012年 Peking University. All rights reserved.
//

#import "XiaoximenTimelineViewController.h"
#import "XiaoximenAppDelegate.h"
#import "FlipTransition.h"

@interface XiaoximenTimelineViewController () {
	BOOL isTimeLine2Displayed;
}

@end

bool bChangeStartMeter = false;
bool bChangeEndMeter = false;
bool boolMouseUp = false;
bool boolMouseMoving = false;
float mousePointX1 = 0;
float mousePointY1 = 0;
float mousePointX2 = 0;
float mousePointY2 = 0;
float fChangeYOffset = 0;

@implementation XiaoximenTimelineViewController
@synthesize date;
@synthesize parentDataSource;
@synthesize dateString;
@synthesize selectedTimeArray = _selectedTimeArray;
@synthesize timeIntervals = _timeIntervals;
@synthesize startTimeLabel;
@synthesize naviItem;
@synthesize startMeter;
@synthesize endTimeLabel;
@synthesize endMeter;
@synthesize timeLine;
@synthesize timeLine2;


- (NSArray *)selectedTimeArray
{
	if (_selectedTimeArray == nil) {
		_selectedTimeArray = [[NSMutableArray alloc] init];
	}
	return _selectedTimeArray;
}
- (NSArray *)timeIntervals
{
	if (_timeIntervals == nil) {
		_timeIntervals = [[NSMutableArray alloc] init];
	}
	return _timeIntervals;
}

- (IBAction)onBack:(id)sender {
	[self dismissModalViewControllerAnimated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	
	self.naviItem.title = dateString;
	
	[self confirmTimeInterval:nil];
	isTimeLine2Displayed = NO;
	
	[self.timeLine2 removeFromSuperview];
}

- (void)viewDidUnload
{
	[self setNaviItem:nil];
	[self setStartTimeLabel:nil];
	[self setEndTimeLabel:nil];
	[self setTimeLine:nil];
	[self setTimeLine2:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (int) translateToYFromTime:(float)time{
	return 55 + time * 13;
}
- (int) translateToTimeFromY:(float)y{
	if (y < 55 - 7) return -1;
	return ((int)(y) - 48)/ 13;
}
- (void)confirmTimeInterval:(id)sender
{
	if ([self.selectedTimeArray containsObject:[NSString stringWithFormat:@"%@-%@",self.startTimeLabel.text,self.endTimeLabel.text]]) {
		return ;
	}
	if (self.timeIntervals.count > 0) {
		UIButton *confirmButton = [self.timeIntervals lastObject];
		[confirmButton setBackgroundColor:_ColorConfirm];
		[confirmButton setTitle:[NSString stringWithFormat:@"%@-%@",self.startTimeLabel.text,self.endTimeLabel.text] forState:UIControlStateNormal];
		[confirmButton removeTarget:self action:@selector(confirmTimeInterval:) forControlEvents:UIControlStateHighlighted];
		[self.selectedTimeArray addObject:[NSString stringWithFormat:@"%@-%@",self.startTimeLabel.text,self.endTimeLabel.text]];
	} else {
		self.startTimeLabel.text = @"06:00";
		self.endTimeLabel.text = @"08:00";
	}
	 
	UIButton *waitToConfirmButton = [[UIButton alloc] init];
	[self.timeIntervals addObject:waitToConfirmButton];
	
	int newStartTime = [[self.endTimeLabel.text substringToIndex:2] intValue];
	if (newStartTime == 24) newStartTime = 0;
	int newEndTime = newStartTime+[[self.endTimeLabel.text substringToIndex:2] intValue]-[[self.startTimeLabel.text substringToIndex:2] intValue];
	if (newEndTime > 24) newEndTime = 24;
	[self updateStartMeter:[self translateToYFromTime:newStartTime]];
	[self updateEndMeter:[self translateToYFromTime:newEndTime]+19];
	
	[waitToConfirmButton setBackgroundColor:_ColorWaitToConfirm];
	[waitToConfirmButton setTitle:@"轻触此处以确认" forState:UIControlStateNormal];
	[waitToConfirmButton.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
	[waitToConfirmButton setTitleColor:_ColorTextWaitToConfirm forState:UIControlStateNormal];
	[waitToConfirmButton addTarget:self action:@selector(confirmTimeInterval:) forControlEvents:UIControlStateHighlighted];
	[self updateWaitToConfirmButton];
	[self.view addSubview:waitToConfirmButton];
}
- (void)updateWaitToConfirmButton
{
	UIButton *waitToConfirmButton = [self.timeIntervals lastObject];
	[waitToConfirmButton setFrame:CGRectMake(30, 
											 self.startTimeLabel.frame.origin.y+self.startTimeLabel.frame.size.height, 
											 250, self.endTimeLabel.frame.origin.y - (self.startTimeLabel.frame.origin.y+self.startTimeLabel.frame.size.height))];
}
- (void)updateStartMeter:(float)newStartMeterY
{
	[self.startMeter setFrame:CGRectMake(self.startMeter.frame.origin.x, 
										 newStartMeterY, 
										 self.startMeter.frame.size.width, 
										 self.startMeter.frame.size.height)];
	[self.startTimeLabel setFrame:CGRectMake(self.startTimeLabel.frame.origin.x, 
											 newStartMeterY - 3, 
											 self.startTimeLabel.frame.size.width, 
											 self.startTimeLabel.frame.size.height)];
	self.startTimeLabel.text = [NSString stringWithFormat:@"%02d:00", [self translateToTimeFromY:newStartMeterY]];
	[self updateWaitToConfirmButton];
}
- (void)updateEndMeter:(float)newEndMeterY
{
	[self.endMeter setFrame:CGRectMake(self.endMeter.frame.origin.x, 
									   newEndMeterY, 
									   self.endMeter.frame.size.width, 
									   self.endMeter.frame.size.height)];
	[self.endTimeLabel setFrame:CGRectMake(self.endTimeLabel.frame.origin.x, 
										   newEndMeterY + 2, 
										   self.endTimeLabel.frame.size.width, 
										   self.endTimeLabel.frame.size.height)];
	self.endTimeLabel.text = [NSString stringWithFormat:@"%02d:00", [self translateToTimeFromY:newEndMeterY-19]];
	[self updateWaitToConfirmButton];
}

// Handles the start of a touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch * touch = [[event touchesForView:self.view] anyObject];
	CGPoint location = [touch locationInView:self.view];
	
	mousePointX1 = location.x/((float)320);
	mousePointY1 = location.y/((float)480);
	
	float timeIntervalBetweenStartAndEnd = self.endMeter.frame.origin.y - (self.startMeter.frame.origin.y+self.startMeter.frame.size.height);
	float padding = timeIntervalBetweenStartAndEnd / 2 < 26 ? timeIntervalBetweenStartAndEnd / 2 : 26;
	if (self.startMeter.frame.origin.y-26 <= location.y && location.y <= self.startMeter.frame.origin.y+self.startMeter.frame.size.height+padding) {
		bChangeStartMeter = true;
		fChangeYOffset = location.y - self.startMeter.frame.origin.y;
	} else if (self.endMeter.frame.origin.y-padding <= location.y && location.y <= self.endMeter.frame.origin.y+self.endMeter.frame.size.height+26) {
		bChangeEndMeter = true;
		fChangeYOffset = location.y - self.endMeter.frame.origin.y;
	}
	
	//NSLog(@"touches Begin at x = %f, y = %f", location.x, location.y);
	//NSLog(@"touches Begin at x = %f, y = %f", mousePointX1, mousePointY1);
}

// Handles the continuation of a touch.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{  
	UITouch * touch = [[event touchesForView:self.view] anyObject];
	CGPoint location = [touch locationInView:self.view];
	
	boolMouseMoving=true;
	
	mousePointX2 = location.x/((float)320);
	mousePointY2 = location.y/((float)480);
	
	if (bChangeStartMeter) {
		float newStartMeterY = location.y - fChangeYOffset < self.endMeter.frame.origin.y - 33 ? location.y - fChangeYOffset : self.endMeter.frame.origin.y - 33;
		if (newStartMeterY < 55) newStartMeterY = 55;
		[self updateStartMeter:newStartMeterY];
	} else if (bChangeEndMeter) {
		float newEndMeterY = location.y - fChangeYOffset > self.startMeter.frame.origin.y + 33 ? location.y - fChangeYOffset : self.startMeter.frame.origin.y + 33;
		if (newEndMeterY > 386) newEndMeterY = 386;
		[self updateEndMeter:newEndMeterY];
	}
	
	//NSLog(@"touches Move at x = %f, y = %f", location.x, location.y);
	//NSLog(@"touches Move at x = %f, y = %f", mousePointX2, mousePointY2);
}

// Handles the end of a touch event when the touch is a tap.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch * touch = [[event touchesForView:self.view] anyObject];
	CGPoint location = [touch locationInView:self.view];
	
	boolMouseUp = true;
	mousePointX1 = mousePointX2 = location.x/((float)320);
	mousePointY1 = mousePointY2 = location.y/((float)480);
	boolMouseMoving = false;
	
	if (bChangeStartMeter) {
		int newStartMeterY = [self translateToYFromTime:[[self.startTimeLabel.text substringToIndex:2] intValue]];
		[self updateStartMeter:newStartMeterY];
	} else if (bChangeEndMeter) {
		int newEndMeterY = [self translateToYFromTime:[[self.endTimeLabel.text substringToIndex:2] intValue]]+19;
		[self updateEndMeter:newEndMeterY];
	}
	
	bChangeStartMeter = false;
	bChangeEndMeter = false;
	
	//NSLog(@"touches End at x = %f, y = %f", location.x, location.y);
	//NSLog(@"touches End at x = %f, y = %f", mousePointX1, mousePointY1);
}

// Handles the end of a touch event.
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
	// If appropriate, add code necessary to save the state of the application.
	// This application is not saving state.
}

- (IBAction)onComplete:(id)sender {
	[self.parentDataSource addDate:self.dateString Times:self.selectedTimeArray];
	[self dismissModalViewControllerAnimated:YES];
}

- (void)changeDayByAddingTimeInterval:(int)time {
	
	// Record
	[self.parentDataSource addDate:self.dateString Times:self.selectedTimeArray];
	
	// Setup FlipTransition
	FlipTransition *ft = [[FlipTransition alloc] init];
	if (time > 0)
		ft.transitionType = FlipTransitionLeft;
	else 
		ft.transitionType = FlipTransitionRight;
	[[HMGLTransitionManager sharedTransitionManager] setTransition:ft];
	[[HMGLTransitionManager sharedTransitionManager] beginTransition:self.view];
	
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy年MM月dd日";
	self.date = [self.date dateByAddingTimeInterval:time];
	self.dateString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:self.date]];
	self.naviItem.title = self.dateString;
	
	[self.timeLine removeFromSuperview];
	[self.view addSubview:self.timeLine];
	for (UIButton *timeInterval in self.timeIntervals) {
		[timeInterval removeFromSuperview];
	}
	
	_selectedTimeArray = nil;
	_timeIntervals = nil;
	[self confirmTimeInterval:nil];
	
	[self.startMeter removeFromSuperview];
	[self.endMeter removeFromSuperview];
	[self.startTimeLabel removeFromSuperview];
	[self.endTimeLabel removeFromSuperview];
	
	[self.view addSubview:self.startMeter];
	[self.view addSubview:self.endMeter];
	[self.view addSubview:self.startTimeLabel];
	[self.view addSubview:self.endTimeLabel];
	
	[[HMGLTransitionManager sharedTransitionManager] commitTransition];
}
- (IBAction)onPrevDay:(id)sender {
	[self changeDayByAddingTimeInterval:-24*60*60];
}

- (IBAction)onNextDay:(id)sender {
	[self changeDayByAddingTimeInterval:24*60*60];
}
@end
